import _ from 'lodash'
import { Button, message, Upload, UploadFile } from 'antd'
import { PlusOutlined } from '@ant-design/icons'

import { filePick } from '@/utils/filePick'
import { fileMax, fileSizeTip, filesMax, filesSizeTip } from './utils'

export interface IFile {
  fileName: string
  file: File
}

export const Files = ({
  disabled,
  files = [],
  onFilesChange = _.noop,
}: {
  disabled?: boolean
  files?: IFile[]
  onFilesChange?: (files: IFile[]) => void
}) => {
  const showList: UploadFile[] = []
  files.forEach(d => showList.push({ uid: d.fileName, name: d.fileName }))

  // 规则：https://postmarkapp.com/developer/user-guide/send-email-with-api
  const onFilePick = () => {
    filePick({
      multiple: true,
      onFilePick: pickFiles => {
        pickFiles = _.uniqBy(pickFiles, f => f.name) // 去重

        if (pickFiles.some(f => f.size / 1024 / 1025 > fileMax - 0.1)) {
          return void message.error(fileSizeTip)
        }

        const pickSize = pickFiles.map(f => f.size).reduce((a, b) => a + b, 0) / 1024 / 1024
        const size = files.map(d => d.file.size).reduce((a, b) => a + b, 0) / 1024 / 1024
        if (pickSize + size > filesMax - 0.5) {
          return void message.error(filesSizeTip)
        }

        const notSupportedExts =
          `vbs,exe,bin,bat,chm,com,cpl,crt,hlp,hta,inf,ins,isp,jse,lnk,mdb,pcd,pif,reg,scr,sct,shs,vbe,vba,wsf,wsh,wsl,msc,msi,msp,mst`.split(
            ',',
          )
        if (pickFiles.some(f => notSupportedExts.some(e => f.name.toLocaleLowerCase().endsWith(e)))) {
          return void message.error(`包含不支持的文件格式`)
        }

        onFilesChange(files.concat(pickFiles.map(f => ({ fileName: f.name, file: f }))))
      },
    })
  }

  return (
    <div style={{ maxWidth: 600 }}>
      <Upload
        openFileDialogOnClick={false}
        fileList={showList}
        onRemove={({ name }) => {
          const newLocalFiles = files.filter(d => d.fileName !== name)
          if (newLocalFiles.length !== files.length) {
            onFilesChange(newLocalFiles)
          }
        }}
      >
        <Button icon={<PlusOutlined />} disabled={disabled} onClick={onFilePick}>
          添加附件
        </Button>
      </Upload>
    </div>
  )
}
